/**
 * Progetto PRAISED.
 * 25/gen/2011
 */
package it.uniroma3.dia.praised.core.dictionary;

import it.uniroma3.dia.praised.core.exception.DictionaryException;
import it.uniroma3.dia.praised.core.model.CandidateProteinName;
import it.uniroma3.dia.praised.core.model.InputText;
import it.uniroma3.dia.praised.core.model.ProteinName;
import it.uniroma3.dia.praised.core.model.Rank;

import java.util.ArrayList;
import java.util.Collections;
//import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author Accosta Augusto
 * @author Lopez Elisabetta
 *
 */
public class RepositoryChecker {
	
	private List<CandidateProteinName> candidateList;
	
	/**
	 * 
	 */
	public RepositoryChecker() {
		this.candidateList = new LinkedList<CandidateProteinName>();
	}
	
	/**
	 * 
	 * @param inputText
	 * @param proteinList
	 * @return
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 */
	public List<CandidateProteinName> extractCandidates(InputText inputText, List<ProteinName> proteinList) throws DictionaryException, InterruptedException, ExecutionException {
		ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*4);
		List<Future<CandidateProteinName>> candidatesFuture = new ArrayList<Future<CandidateProteinName>>(proteinList.size());
		
		for (ProteinName proteinName : proteinList) {
			candidatesFuture.add(pool.submit(new CalculateRankWorker(inputText, proteinName, new Rank())));
		}
		
		for (Future<CandidateProteinName> future : candidatesFuture) {
			if(future.get() != null)
				this.candidateList.add(future.get());
		}
		
//		Iterator<Future<CandidateProteinName>> it =  candidatesFuture.iterator();
//		while (it.hasNext()) {
//			Future<CandidateProteinName> future = it.next();
//			try {
//				if(future.get() != null)
//					this.candidateList.add(future.get());
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			} catch (ExecutionException e) {
//				e.printStackTrace();
//			}
//			it.remove();
//		}
		
		pool.shutdown();
		
		Collections.sort(this.candidateList);
		
		return this.candidateList;
	}
	
}
